package com.example.demo.codegenerate.service;

import com.example.demo.dao.Creation;
import com.example.demo.service.BaseService;
import com.example.demo.codegenerate.util.CodeGenerateUtil;
import com.example.demo.codegenerate.dao.JeecgColumnDao;
import com.example.demo.codegenerate.dao.JeecgTableDao;
import com.example.demo.codegenerate.domain.JeecgColumn;
import com.example.demo.codegenerate.domain.JeecgTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.UUID;

@Service
@Transactional
public class JeecgTableService extends BaseService<JeecgTable, JeecgTableDao> {

    @Autowired
    private JeecgColumnDao jeecgColumnDao;

    @Override
    public void delete(String id) {
        super.delete(id);
        jeecgColumnDao.deleteByCreations(new Creation("jeecg_table_id", Creation.Operation.eq, id));
    }

    @Override
    public void insert(JeecgTable jeecgTable) {
        if(!StringUtils.isEmpty(jeecgTable.getId())){
            delete(jeecgTable.getId());
        }

        jeecgTable.setId(UUID.randomUUID().toString());
        super.insert(jeecgTable);

        int sequence = 0;

        for (JeecgColumn jeecgColumn : jeecgTable.getJeecgColumnList()) {
            jeecgColumn.setId(UUID.randomUUID().toString());
            jeecgColumn.setJeecgTableId(jeecgTable.getId());
            jeecgColumn.setSequence(sequence);
            jeecgColumn.setDatabaseType(CodeGenerateUtil.javaType2databaseType(jeecgColumn.getJavaType(), jeecgColumn.getCtrlType()));
            sequence++;
        }
        jeecgColumnDao.batchInsert(jeecgTable.getJeecgColumnList());
    }
}
